//
//  HomeView.swift
//  shop
//
//  Created by chen on 2025/5/12.
//

import SwiftUI

struct HomeView: View {
    
    @StateObject private var vm: HomeViewModel = HomeViewModel.shared
    @EnvironmentObject private var router: Router
    
    var body: some View {
        ZStack{
            Color.gray.opacity(0.1)
                .ignoresSafeArea()
            
            VStack(spacing: 0){
                // 搜索框
                SearchCard(router: router)
                    .padding(.top, 5)
                    .padding(.bottom, 5)
                    .background(.white)
                
                // 商品列表
                ScrollView(showsIndicators: false) {
                    // banner列表
                    BannerCard(vm: vm, router: router)
                        .padding(.top, 4)

                    WaterfallGrid(items: vm.goodsResp.list) { item in
                        Button {
                            router.to(.detailView(id: item.id))
                        } label: {
                            ProductCard(item: item)
                                .onAppear{
                                    withAnimation {
                                        if !vm.lastId.isEmpty && vm.lastId == item.goodsId {
                                            vm.getGoodsList()
                                        }
                                    }
                                }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    .onAppear{
                        vm.getGoodsList()
                    }
                }
                
                Spacer(minLength: 1)
            }
        }
        .navigationBarBackButtonHidden(true)
    }
}

#Preview {
    HomeView()
        .environmentObject(Router.shared)
}
